﻿/**
* loupe - an image magnifier for jQuery
* (C) 2010 jdbartlett, MIT license
* http://github.com/jdbartlett/loupe
*/
(function($) {
    $.fn.loupe = function(arg) {
        var options = $.extend({
                loupe: 'loupe',
                width: 40,
                height: 40,
                big_width: 240, big_height: 100
            }, arg || { });

        return this.length ? this.each(function() {
            //var $this = $(this), $big, $loupe,
            var $this = $(this), $loupe,
                $small = $this.is('img') ? $this : $this.find('img:first'),
                move, hide = function() { $loupe.hide(); },
                time;

            if ($this.data('loupe') != null) {
                return $this.data('loupe', arg);
            }

            move = function(e) {
                var os = $small.offset(),
                    sW = $small.outerWidth(),
                    sH = $small.outerHeight(),
                    oW = options.width / 2,
                    oH = options.height / 2;

                if (!$this.data('loupe') ||
                    e.pageX > sW + os.left + 10 || e.pageX < os.left - 10 ||
                        e.pageY > sH + os.top + 10 || e.pageY < os.top - 10) {
                    return hide();
                }

                time = time ? clearTimeout(time) : 0;

                $loupe.show().css({
                        left: e.pageX - oW,
                        top: e.pageY - oH
                    });
                //$big.css({
                //    left: -(((e.pageX - os.left) / sW) * $big.width() - oW) | 0,
                //    top: -(((e.pageY - os.top) / sH) * $big.height() - oH) | 0
                //    });
                var xpos = (-(((e.pageX - os.left) / sW) * options.big_width - oW) | 0) + 'px';
                var ypos = (-(((e.pageY - os.top) / sH) * options.big_height - oH) | 0) + 'px';
                $loupe.css('background-position', xpos + ' ' + ypos);
                return e;
            };

            $loupe = $('<div />')
                .addClass(options.loupe)
                .css({
                        width: options.width,
                        height: options.height,
                        position: 'absolute',
                        overflow: 'hidden',
                        background: '#fbfbfb url(' + $this.attr($this.is('img') ? 'src' : 'href') + ') 0px 0px no-repeat'
                    })
                //راضاکی
                //.append($big = $('<img />').attr('src', $this.attr($this.is('img') ? 'src' : 'href')).css('position', 'absolute'))
                .mousemove(move)
                .hide()
                .appendTo('body');

            $this.data('loupe', true)
                .mouseenter(move)
                .mouseout(function() {
                    time = setTimeout(hide, 10);
                });
        }) : this;
    };
}(jQuery));